package com.itheima.service.impl;

import com.itheima.annotation.Log;
import com.itheima.dao.DeptMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;


    @Override
    public List<Dept> selectAll() {
        return deptMapper.selectAll();
    }

    @Override
    public boolean deleteById(Integer id) {
        //i >0 代表删除成功
        int i = deptMapper.deleteById(id);
        return i > 0;
    }

    @Log
    @Override
    public Result insert(Dept dept) {
        if (checkIsExist(dept)) {
            return Result.fail("部门名称已存在");
        }
        int insert = deptMapper.insert(dept);
        return insert > 0 ? Result.success("添加成功") : Result.fail("添加失败");
    }

    @Override
    public Dept selectById(Integer id) {
        return deptMapper.selectById(id);
    }

    @Log
    @Override
    public Result update(Dept dept) {
        if (checkIsExist(dept)) {
            return Result.fail("部门名称已存在");
        }
        int i = deptMapper.update(dept);
        return i > 0 ? Result.success("修改成功") : Result.fail("修改失败");
    }


    /**
     * 效验名称是否存在
     * @return
     */
    public boolean checkIsExist(Dept dept) {
        Dept dept1 = deptMapper.selectByName(dept.getName());
        if (dept1 != null && !dept1.getId().equals(dept.getId())) {
            return true;
        }
        return false;
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Log
    @Override
    public Result deleteByIds(Integer[] ids) {
        int i = deptMapper.deleteByIds(ids);
        return Result.success("成功删除"+i+"条数据");
    }

    /**
     * 批量插入
     */
    @Log
    @Override
    public Result insertBatch(List<Dept> insertDepts) {
        for (Dept insertDept : insertDepts) {
            if (checkIsExist(insertDept)) {
                return Result.fail("存在重复的部门名称");
            }
        }
        int i = deptMapper.insertBatch(insertDepts);
        return i > 0 ? Result.success("批量成功插入"+i+"条数据") : Result.fail("批量添加失败");
    }
}
